package com.itmg.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.itmg.dao.CacheDataDAO;
import com.itmg.dao.model.CacheDataModel;

public class CacheDataDAOImpl extends SqlMapClientDaoSupport implements CacheDataDAO{


	public void saveInfo(CacheDataModel model) throws Exception {
		 Connection con = null;
		 String sql ="insert into shop_cache_data (" +
			 		 "productMd5," +
			 		 "keywords," +
			 		 "category," +
			 		 "model_name," +
			 		 "brand_name," +
			 		 "price," +
			 		 "create_time) values (" +
			 		 "?," +
			 		 "?," +
			 		 "?," +
			 		 "?," +
			 		 "?," +
			 		 "?," +
			 		 "?)";
		 try{
			 con = getSqlMapClientTemplate().getDataSource().getConnection();
			 PreparedStatement ps = con.prepareStatement(sql);
			 ps.setString(1, model.getProductMd5());
			 ps.setString(2, model.getKeywords());
			 ps.setString(3, model.getCategory());
			 ps.setString(4, model.getModel_name());
			 ps.setString(5, model.getBrand_name());
			 ps.setString(6, model.getPrice());
			 ps.setTimestamp(7, model.getCreate_time());
			 ps.executeUpdate();
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
	}
	
	public CacheDataModel getInfo(String productMd5) throws Exception {
		CacheDataModel model = new CacheDataModel();
		Connection con = null;
		 String sql ="select * from shop_cache_data where productMd5=?";
		 try{
			 con = getSqlMapClientTemplate().getDataSource().getConnection();
			 PreparedStatement ps = con.prepareStatement(sql);
			 ps.setString(1, productMd5);
			 ResultSet rs = ps.executeQuery();
			 while(rs.next()){
				 model.setId(rs.getInt("id"));
				 model.setCategory(rs.getString("category"));
				 model.setKeywords(rs.getString("keywords"));
				 model.setModel_name(rs.getString("model_name"));
				 model.setBrand_name(rs.getString("brand_name"));
				 model.setPrice(rs.getString("price"));
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		 }
		return model;
	}
	
	//删除所有数据
	public void deleteAll() throws Exception{
		Connection con = null;
		String sql = "delete from shop_cache_data";
		try {
			con = getSqlMapClientTemplate().getDataSource().getConnection();
			Statement ps = con.createStatement();
			ps.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				con.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
